package org.example.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.example.bean.Book;
import org.example.bean.Discount;
import org.example.bean.User;
import org.example.handler.BookSaveException;
import org.example.mapper.BookMapper;
import org.example.service.BookService;
import org.example.service.DiscountService;
import org.example.util.JsonResult;
import org.example.util.ResultTool;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.ResourceUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.NumberFormat;
import java.time.LocalDate;
import java.util.List;
import java.util.UUID;

/**
 * @Auther:Liu
 * @Testname:BookServiceImpl
 * @Date:2025/8/6 11:42
 */
@Slf4j
@Service
public class BookServiceImpl extends ServiceImpl<BookMapper, Book> implements BookService {
    @Resource
    private BookMapper bookMapper;

    @Resource
    private DiscountService discountService;

    @Resource
    private StringRedisTemplate stringRedisTemplate;


    @Cacheable(cacheNames = "BookList", key = "#page")
    public JsonResult find(int page, int size) {
        IPage<Book> iPage = new Page<>(page, size);
        List<Book> list = list(iPage);
        for (Book book : list) {
            JsonResult<Discount> priceByBookId = discountService.findDiscountPriceByBookId(book.getId());
            if (priceByBookId.getSuccess()) {
                book.setDiscountRate(priceByBookId.getData().getDiscountRate());
                NumberFormat instance = NumberFormat.getInstance();
                instance.setMaximumFractionDigits(2);
                String format = instance.format(priceByBookId.getData().getDiscountRate() * book.getPrice());
                book.setDiscountId(priceByBookId.getData().getId());
                book.setDiscountPrice(Double.valueOf(format));
            } else {
                book.setDiscountRate(1.0);
                book.setDiscountPrice(book.getPrice());
            }
        }
        iPage.setRecords(list);
        return ResultTool.success(iPage);
    }

    @Override
    public JsonResult saveBook(Book book, MultipartFile file) throws IOException {
        String filePath = ResourceUtils.getURL("classpath:").getPath() + "/static/img";
//        String filePath="C:/VueWorkSpace/Html/vue-2025/src/assets";
        String originalFilename = file.getOriginalFilename();
        String type = originalFilename.substring(originalFilename.lastIndexOf("."));
        String fileName = UUID.randomUUID() + type;
        File src = new File(filePath, fileName);
        file.transferTo(src);
//        book.setImageName(filePath+"/"+fileName);
        book.setImageName("http://localhost:8000/img/" + fileName);
        boolean b = save(book);
        if (!b) {
            throw new BookSaveException("图书创建失败");
        } else {
            return ResultTool.success("添加成功");
        }
    }

    @Override
    public JsonResult findBookById(String id) {
        Book book = getById(id);
        return ResultTool.success(book);
    }

    @CachePut(cacheNames = "BookList", key = "#book.id")
    @CacheEvict(cacheNames = "BookList", allEntries = true)
    public JsonResult UpdateBook(Book book) {
        UpdateWrapper<Book> wrapper = new UpdateWrapper<>();
        wrapper.eq("id", book.getId());
        wrapper.set("image_name", book.getImageName());
        wrapper.set("name", book.getName());
        wrapper.set("author", book.getAuthor());
        wrapper.set("price", book.getPrice());
        wrapper.set("publisher", book.getPublisher());
        wrapper.set("description", book.getDescription());
        wrapper.set("status", book.getStatus());
        wrapper.set("update_time", LocalDate.now());
        boolean b = update(wrapper);
        if (!b) {
            throw new BookSaveException("图书更新失败");
        } else {
            return ResultTool.success("更新成功");
        }
    }

    @CacheEvict(cacheNames = "BookList", allEntries = true, key = "#id")
    public JsonResult deleteBook(String id) {
        boolean b = removeById(id);
        if (!b) {
            throw new BookSaveException("图书删除失败");
        } else {
            return ResultTool.success("删除成功");
        }
    }

    @Override
    public JsonResult findBookByCateGoryId(String cateGoryId) {
        QueryWrapper<Book> wrapper = new QueryWrapper<>();
        wrapper.eq("category_id", cateGoryId);
        Long count = bookMapper.selectCount(wrapper);
        if (count > 0) {
            return ResultTool.fail(201, "分类下有图书");
        }
        return ResultTool.success("success");
    }

    @Override
    public JsonResult findBookByCateGoryIdToShow(String cateGoryId) {
        QueryWrapper<Book> wrapper = new QueryWrapper<>();
        wrapper.eq("category_id", cateGoryId);
        List<Book> list = list(wrapper);
        return ResultTool.success(list);
    }

    /**
     * 查询图书
     * @return
     */
    @Override
    public JsonResult findAllBook() {
        return ResultTool.success(list());
    }
}
